// pages/assets/assets.js
const api = require('../../utils/api.js')
const app = getApp()

Page({
    data: {
        assets: [],
        labs: [],
        categories: [],
        keyword: '',
        selectedLab: '',
        selectedCategory: '',
        selectedStatus: '',
        selectedStatusLabel: '',
        showFilters: false,
        statusOptions: [
            { value: '', label: '全部' },
            { value: 'in_use', label: '在用' },
            { value: 'idle', label: '闲置' },
            { value: 'repairing', label: '维修中' },
            { value: 'scrapped', label: '已报废' }
        ],
        statusText: {
            'in_use': '在用',
            'idle': '闲置',
            'repairing': '维修中',
            'scrapped': '已报废'
        },
        page: 1,
        pageSize: 20,
        hasMore: true,
        loading: false,
        hasPermission: false  // 是否有查看资产的权限（教师/学生）
    },

    onLoad() {
        // 检查用户角色权限
        const userRole = app.globalData.userRole
        const isAdmin = app.globalData.isAdmin

        // 管理员、教师和学生可以查看资产
        const hasPermission = isAdmin || userRole === 'teacher' || userRole === 'student'

        this.setData({ hasPermission })

        // 只有有权限的用户才加载数据
        if (hasPermission) {
            this.loadLabs()
            this.loadCategories()
            this.loadAssets()
        }
    },

    onShow() {
        // 更新权限状态
        const userRole = app.globalData.userRole
        const isAdmin = app.globalData.isAdmin
        const hasPermission = isAdmin || userRole === 'teacher' || userRole === 'student'

        this.setData({ hasPermission })
    },

    // 加载机房列表
    async loadLabs() {
        try {
            const data = await api.request({ url: '/lab/list' })
            this.setData({ labs: [{ id: '', name: '全部' }, ...data.list] })
        } catch (error) {
            console.error('加载机房失败', error)
        }
    },

    // 加载分类列表
    async loadCategories() {
        try {
            const data = await api.request({ url: '/asset/categories' })
            this.setData({ categories: [{ id: '', name: '全部' }, ...data.list] })
        } catch (error) {
            console.error('加载分类失败', error)
        }
    },

    // 加载资产列表
    async loadAssets(reset = false) {
        if (this.data.loading) return

        if (reset) {
            this.setData({ page: 1, assets: [], hasMore: true })
        }

        this.setData({ loading: true })

        try {
            const params = {
                page: this.data.page,
                pageSize: this.data.pageSize
            }

            if (this.data.keyword) params.keyword = this.data.keyword
            if (this.data.selectedLab) params.labId = this.data.selectedLab
            if (this.data.selectedCategory) params.categoryId = this.data.selectedCategory
            if (this.data.selectedStatus) params.status = this.data.selectedStatus

            const data = await api.request({ url: '/assets', data: params })

            // 有权限的用户可以查看完整信息
            const processedList = data.list

            const newAssets = reset ? processedList : [...this.data.assets, ...processedList]
            this.setData({
                assets: newAssets,
                hasMore: data.list.length === this.data.pageSize,
                page: this.data.page + 1
            })
        } catch (error) {
            console.error('加载资产失败', error)
            wx.showToast({ title: '加载失败', icon: 'none' })
        } finally {
            this.setData({ loading: false })
        }
    },

    // 搜索关键词输入
    onKeywordInput(e) {
        this.setData({ keyword: e.detail.value })
    },

    // 执行搜索
    onSearch() {
        this.loadAssets(true)
    },

    // 显示筛选
    showFilterModal() {
        this.setData({ showFilters: !this.data.showFilters })
    },

    // 机房筛选
    onLabChange(e) {
        const index = e.detail.value
        const lab = this.data.labs[index]
        this.setData({
            selectedLab: lab.id,
            selectedLabName: lab.name
        })
        this.loadAssets(true)
    },

    // 分类筛选
    onCategoryChange(e) {
        const index = e.detail.value
        const category = this.data.categories[index]
        this.setData({
            selectedCategory: category.id,
            selectedCategoryName: category.name
        })
        this.loadAssets(true)
    },

    // 状态筛选
    onStatusChange(e) {
        const index = e.detail.value
        const status = this.data.statusOptions[index]
        this.setData({
            selectedStatus: status.value,
            selectedStatusLabel: status.label
        })
        this.loadAssets(true)
    },

    // 查看详情
    viewDetail(e) {
        const { id } = e.currentTarget.dataset
        wx.navigateTo({
            url: `/pages/asset-detail/asset-detail?id=${id}`
        })
    },

    // 下拉刷新
    onPullDownRefresh() {
        this.loadAssets(true)
        wx.stopPullDownRefresh()
    },

    // 上拉加载
    onReachBottom() {
        if (this.data.hasMore && !this.data.loading) {
            this.loadAssets()
        }
    }
})
